<?php


function CheckDownloadLinks($order_items){

	// MUST PASS IN THE order_items FIELD FROM THE ORDERS DATA
	// FORMAT IS: 58x1,
	
	$o1 = explode(",",$order_items); $i=0; $data = array();

	foreach($o1 as $items){
	
	$o2 = explode("x",$items);
	
	//$o2[0] <-- ITEM ID
	//$o2[1] <-- QUANTITY
	
	 $post_data = get_post( $o2[0] );
	 
	 $data[$i]['id']  	= $o2[0];	
	 $data[$i]['name'] 	= $post_data->post_title;
	 $data[$i]['qty']  	= $o2[1];
	 $data[$i]['file'] 	= get_post_meta($o2[0], "file", true);
	 $data[$i]['image'] = get_post_meta($o2[0], "image", true);
	 
	 $i++;
	 
	}
	
	return $data;
}


	function getDownloadData($itemID, $ignore_credit=0){

	global $wpdb; global $userdata; get_currentuserinfo();
	
	$price = get_post_meta($itemID, "price", true);
 	$file = get_post_meta($itemID, "file", true);

	// GET THE FILE STORAGE PATH
	$server_path = get_option("download_server_path");
	if($server_path ==""){
	
		$server_path = get_option("imagestorage_path");
		if($server_path ==""){	
			die("<h1>Download Server Path Error</h1><p>The download server paths have not been setup via the admin area. Please contact the server admin.</p>");
		}
	}

	// USER MUST BE LOGGED IN TO DOWNLOAD
	if($ignore_credit ==0){ if(!isset($userdata->ID) || $userdata->ID ==""){
		header("location: wp-login.php?action=login");exit();
	} }
 
 	if($ignore_credit ==1){ $price=0; } // used for 
 
	// MAKE SURE WE HAVE ENOUGH CREDITS
	if( ( $userdata->aim >= $price ) || ( $price == 0 ) ){
 
		if($file ==""){
	
			die("<h1>Download Link Missing. Please contact support.</h1>");
		
		}else{ 
	 
			$file_path = $server_path . $file;

			//if(file_exists($file_path)){

				// REMOVE DOWNLOAD CREDITS	  
				$wpdb->query("UPDATE $wpdb->usermeta SET meta_value=meta_value-".round($price,1)." WHERE meta_key='aim' AND user_id=('".$userdata->ID."') LIMIT 1");

				$sub = substr($file_path,-3);
				$file_size =@filesize($file_path);			
				header('Last-Modified: '.date('r')); 
				header('Content-Description: File Transfer'); 
				header('Content-Type: '.returnMIMEType($sub).'');
				header("Content-disposition: attachment; filename=".$file."");
				header("Content-Length: ".$file_size."");
				ob_clean();
				flush();
				readfile($file_path);
				exit;

			//}else{
			//	die("<h1> Download File Doesnt Exist</h1>".$file_path);
			//}
		
		}

	}else{
	
		die("<h1>Insufficent Credits Remaining</h1>");

	}

	return $ReturnArray;
 
	
	}
	

?>